import { Tabs, Badge, Swiper } from 'antd-mobile'
import type { SwiperRef } from 'antd-mobile/es/components/swiper'
import { useStreams } from '@/lib/utils'
import { useContactType } from '@/logics/contacts'
import { NoQywxNotice } from '@/mobile/views/mine/no-qywx-notice'
import services from '@/services'
import { ContactType } from '@/services/contacts'
import { useUnreadOfTypes } from './logics'

export function ContactTypes() {
  const [qywxMap] = useStreams(services.qywxs.alives)
  const unreads = useUnreadOfTypes()

  const types = [
    { type: ContactType.external, name: '客户', render: () => <>客户客户</> },
    { type: ContactType.group, name: '群', render: () => <>群群</> },
    { type: ContactType.internal, name: '员工', render: () => <>员工员工</> },
  ]

  const [type, setType] = useContactType()
  const swiperRef = useRef<SwiperRef>(null)
  function onTabChange(type: ContactType) {
    setType(type)
    const index = types.findIndex(item => item.type === type)
    swiperRef.current?.swipeTo(index)
  }
  function onSwip(index: number) {
    setType(types[index]!.type)
  }

  return <>
    <Tabs css={s.tabs} activeKey={type} onChange={key => onTabChange(key as ContactType)}>
      {types.map(item => {
        const unread = unreads[item.type as keyof typeof unreads]
        const badge = <Badge content={unread || ''}>{item.name}</Badge>
        return <Tabs.Tab key={item.type} title={badge} />
      })}
    </Tabs>

    <Swiper
      css={s.swiper}
      loop
      indicator={() => null}
      ref={swiperRef}
      defaultIndex={types.findIndex(item => item.type === type)}
      onIndexChange={onSwip}
    >
      {types.map(item => {
        return <Swiper.Item key={item.type}>
          {type === item.type ? (
            qywxMap.size <= 0 ? (
              <NoQywxNotice marginTop="9.2vh" />
            ) : (
              item.render()
            )
          ) : null}
        </Swiper.Item>
      })}
    </Swiper>
  </>
}

const s = {
  tabs: css`
    --adm-color-border: none;
    .adm-badge {
      --right: -4px;
    }
  `,
  swiper: css`
    flex: 1;
    .adm-swiper-slide {
      box-sizing: border-box;
      padding-top: 20px;
    }
    .adm-swiper-item {
      height: 100%;
      overflow-y: auto;
    }
  `,
}
